package com.yfk.base.event;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yfk.base.auth.network.cryptor.EncryptionHolder;
import com.yfk.base.auth.network.cryptor.PrivateAppCryptoSHA256;
import com.yfk.base.event.pojo.Event;
import com.yfk.base.event.pojo.QWConfigVO;
import com.yfk.base.http.HttpUtil;
import com.yfk.base.properties.OpenApiProperties;
import com.yfk.web.entity.YFKVO;
import com.yfk.web.entity.YHTVO;
import com.yfk.web.util.BIPUtil;
import com.yfk.web.util.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 事件订阅的回调controller
 */
@Slf4j
@ResponseBody
@RestController
@RequestMapping("/rest/event/v1")
public class EventListenerController {

    private static Logger logger = LoggerFactory.getLogger(EventListenerController.class);

    @Resource
    ReceivedEventDispatcher receivedEventDispatcher;
    @Resource
    OpenApiProperties openApiProperties;
    private ObjectMapper objectMapper = new ObjectMapper();
    @Autowired
    private QWConfigVO qwConfigVO;

    @Autowired
    private YFKVO yfkVO;
    @Autowired
    private YHTVO yhtvo;

    /**
     *  2022-07-29 后创建的应用使用该事件订阅回调
     * @param holder 开放平台请求消息体
     * @return 返回success表示成功接收，抛出异常等其他代表接收失败
     */
    @PostMapping("/new")
    public String onEventNew(@RequestBody EncryptionHolder holder) throws Exception {
        logger.info("###begin--开始事件订阅回调");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(new Date());
        try {
//            if (true) return "success";
            PrivateAppCryptoSHA256 crypto = PrivateAppCryptoSHA256.newCrypto(openApiProperties.getAppKey(), openApiProperties.getAppSecret());
            // 验签解密后的消息体
            String decrypt = crypto.decryptMsg(holder);
            Event event = objectMapper.readValue(decrypt, Event.class);
            // modify by wy at 2025年4月28日
            String type = event.getType(); // 操作类型
            // 获取基础信息，
            JSONObject content = JSONObject.parseObject(event.getContent());
            if (content == null)  return "success";
            JSONObject contentValue = content.getJSONObject("value");
            JSONObject todoTemplateVars = contentValue.getJSONObject("todoTemplateVars");
            String eventType = todoTemplateVars.getString("eventType"); // create:创建、 delete:撤回、complete:已办
            JSONObject json = new JSONObject();
            json.put("appId",this.qwConfigVO.getAppId());
            if(event.getContent() == null){
                return "success";
            }
            logger.info("###数据同步的类型: " + eventType);
            String businessKey = contentValue.getString("businessKey");// 1895b3d2-24c0-11f0-addd-00505683f795
            // 0未完成、1处理中、2已完成、3退回
            String url = "http://" + this.qwConfigVO.getLwip();
            String yhtBaseURL = this.qwConfigVO.getYhtBaseURL();
            String tokenURl = yhtBaseURL + "/iuap-api-auth/open-auth/selfAppAuth/getAccessToken";
            // https://专属化域名/iuap-api-auth/open-auth/selfAppAuth/getAccessToken?appKey=xxx&timestamp=xxx&signature=xxx
            String access_Token = BIPUtil.getAccessToken(tokenURl, this.qwConfigVO.getAppKey(), this.qwConfigVO.getAppSecret());
            if("TODO_CENTER_ADD_TODO".equals(type) && "create".equals(eventType)){ // 添加待办信息
                Object userid = contentValue.getJSONArray("yyUserIds").get(0);
                url += "/api/todo/add";
                String title = contentValue.getString("title");
                String valueContent = contentValue.getString("content");
                json.put("code",businessKey); // 编号，第三方系统内唯一标识
                json.put("name",title); // 事项名称
                json.put("description",valueContent); // 事项描述
                json.put("type",eventType); // 事项类型
                json.put("priority",9); // 优先级，值越高表示优先级越高
                json.put("status", 0); // 完成情况，默认未完成 0未完成、1处理中、2已完成、3退回
                String mobUrl = contentValue.getString("mUrl");
                String mobURL = "http://" + this.qwConfigVO.getYytbj() + "/YHTService/auth?userid="+userid+"&redirectUrl="+mobUrl.replaceAll("&",";");
                json.put("mobileHandleUrl",mobURL); // 事项处理地址（移动端平台跳转链接）
                String webURl = contentValue.getString("webUrl");
                String pcURL = "http://" + this.qwConfigVO.getYytbj() + "/YHTService/auth?userid="+userid+"&redirectUrl="+webURl.replaceAll("&",";");
                json.put("handleUrl", pcURL);
                JSONObject userInfo = getYHTUserInfo(userid.toString(), access_Token, yhtBaseURL, this.qwConfigVO.getGetStaff());
                String userCode = userInfo.getString("code");
                json.put("userNo",userCode );// 经办人工号 工号、身份证两者不能同时为空
                String id = userInfo.getString("id");
                JSONObject userDetail = this.getYHTUserDetail(id, access_Token, yhtBaseURL, this.qwConfigVO.getStaffdetail());
                json.put("userIdNo",userDetail.getString("cert_no"));// 经办人身份证号 工号、身份证两者不能同时为空
                json.put("startDate", date);// 开始时间，默认调用时间 格式yyyy-MM-dd HH:mm:ss
                json.put("endDate","");
            }else if("TODO_CENTER_UPDATE_TODO".equals(type)){
                url += "/api/todo/deal";
                json.put("code",businessKey);
                Integer status = 2; // 默认变成已完成
                if("delete".equals(eventType)){ // 收回审批信息 eventType,delete:删除\complete:正常
                    status = 3;
                }
                json.put("status",status);
            }
            // end modify by wy
            logger.info("###同步企微的数据:"+ json );
            receivedEventDispatcher.dispatch(event, decrypt, holder);
            String s = HttpUtil.sendUamPost(url, json.toJSONString(), "POST");
            if(s==null || "".equals(s)){
                throw new Exception("###友合同消息同步企业微信异常,请求类型:【"+type+"】,请求地址:【"+url+"】,请求参数:【"+json.toJSONString()+"】,企业微信返回信息: " + s);
            }else{
                JSONObject qwRes = JSON.parseObject(s);
                String code = qwRes.getString("code");
                if("200".equals(code)){
                    logger.info("###友合同信息同步企业微信正常,请求类型:【"+type+"】,请求地址:【"+url+"】,请求参数:【"+json.toJSONString()+"】,响应结果: " + s);
                }else {
                    throw new Exception("###友合同信息同步企业微信异常,请求类型:【"+type+"】,请求地址:【"+url+"】,请求参数:【"+json.toJSONString()+"】,响应结果:" + s);
                }
            }


        } catch (Exception e) {
            logger.error("####友合同推送消息到企业微信异常:【 "+ e.getMessage()+" 】");
            return "success";
        }
        logger.info("###end-结束事件订阅回调");
        return "success";
    }

    /**
     * 获取友合同用户信息
     * @param userId
     * @param accessToken
     * @return
     * @throws Exception
     */
    public JSONObject getYHTUserInfo(String userId, String accessToken, String baseURL, String GetStaffURL) throws Exception{
        Map queryParams = new HashMap<>();
        queryParams.put("access_token", accessToken);
        String s = baseURL + "/iuap-api-gateway" + GetStaffURL;
        JSONObject bodyJSON = new JSONObject();
        List<String> userIds = new ArrayList<>();
        userIds.add(userId);
        bodyJSON.put("userId", userIds);
        String res = BIPUtil.getPostQueryParamAndBodyParam(s, queryParams, bodyJSON);
        JSONObject json = JSON.parseObject(res);
        if("200".equals(json.getString("code"))){
            return json.getJSONObject("data").getJSONArray("data").getJSONObject(0);
        }else{
            throw new Exception("根据用户ID获取用户信息异常，平台接口返回信息" + res);
        }
    }


    /**
     * 获取员工详细信息
     * @param ID
     * @param accessToken
     * @return
     * @throws Exception
     */
    public JSONObject getYHTUserDetail(String ID, String accessToken, String baseURL, String getStaffdetailURL) throws Exception{
        Map queryParams = new HashMap<>();
        queryParams.put("access_token", accessToken);
        queryParams.put("id", ID);
        String apiUrl = baseURL + "/iuap-api-gateway" + getStaffdetailURL;
        String res = HttpClientUtil.doGet(apiUrl, null, queryParams);
        JSONObject json = JSON.parseObject(res);
        if("200".equals(json.getString("code"))){
            return json.getJSONObject("data");
        }else{
            throw new Exception("根据用户ID获取用户信息异常，平台接口返回信息" + res);
        }
    }
}
